package com.mall.b2c.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.b2c.domain.member.MemberDomain;
import com.mall.b2c.service.MemberService;
import com.mall.b2c.util.JsonDataGridHelper;
import com.mall.common.bean.Message;
import com.mall.common.bean.Pager;
import com.mall.common.bean.SearchFilter;
import com.mall.common.controller.BaseController;
import com.mall.common.enums.FieldType;
import com.mall.common.exception.NoticeException;
import com.mall.common.hibernate.Finder;
import com.mall.common.util.PasswordUtil;
import com.mall.common.util.ResponseUtils;
import com.mall.common.util.VerifyUtil;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.RequiredStringValidator;
import com.mall.common.validation.annotation.SpecialRegexFieldValidator;
import com.mall.common.validation.annotation.Validations;
import com.mall.common.web.Servlets;


/**
 * 后台Action类 - 会员
 *
 */
@Controller
@RequestMapping("/admin/b2c/member")
public class MemberController extends BaseController {
	@Resource private MemberService memberService;
	
	/**
	 * 会员列表
	 * @return
	 */
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public String list(){
		return "/admin/b2c/member/list";	
	}

	/**
	 * 查询帐号信息
	 * @param customerId 客户id
	 * @param pager
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryData")
	@ResponseBody
	public Pager queryData(Pager pager,HttpServletRequest request){
		Map<String, Object> filterParams = Servlets.getParametersStartingWith(request);
		List<SearchFilter> filters = SearchFilter.parse(filterParams);
		pager = memberService.findPage(pager, filters);
		return JsonDataGridHelper.createJSONData(pager);
	}
	
	/**
	 * 新增帐号
	 * @return
	 */
	@RequestMapping("/add")
	public String add(){
		return "/admin/b2c/member/input";
	}

	/**
	 * 校验用户名是否唯一
	 * @param member
	 * @param oldValue
	 * @return
	 */
	@RequestMapping(value="/checkUsername",method=RequestMethod.POST)
	@ResponseBody
	public String checkUsername(MemberDomain member, String oldValue){
		String newValue = member.getUsername();
		if(memberService.isUnique("username", oldValue, newValue)) {
			return "true";
		} else {
			return "false";
		}
	}

	/**
	 * 校验邮箱是否唯一
	 * @param member
	 * @param oldValue
	 * @return
	 */
	@RequestMapping(value="/checkEmail",method=RequestMethod.POST)
	@ResponseBody
	public String checkEmail(MemberDomain member, String oldValue){
		String newValue = member.getEmail();
		if(memberService.isUnique("email", oldValue, newValue)) {
			return "true";
		} else {
			return "false";
		}
	}

	/**
	 * 校验手机号码是否唯一
	 * @param member
	 * @param oldValue
	 * @return
	 */
	@RequestMapping(value="/checkMobile",method=RequestMethod.POST)
	@ResponseBody
	public String checkMobile(MemberDomain member, String oldValue){
		String newValue = member.getMobile();
		if(memberService.isUnique("mobile", oldValue, newValue)) {
			return "true";
		} else {
			return "false";
		}
	}

	/**
	 * 保存会员
	 * @param member 会员信息
	 * @param response
	 * @return
	 */
	@Validations(
			requiredStrings = {
					@RequiredStringValidator(fieldName="username",message="登录帐号不能为空"),
					@RequiredStringValidator(fieldName="password",message="密码不能为空"),
					@RequiredStringValidator(fieldName="email",message="电子邮箱不能为空")
			},
			specials = {
					@SpecialRegexFieldValidator(fieldName="mobile",fieldType=FieldType.mobile),
					@SpecialRegexFieldValidator(fieldName="telephone",fieldType=FieldType.telephone),
					@SpecialRegexFieldValidator(fieldName="email",fieldType=FieldType.email),
					@SpecialRegexFieldValidator(fieldName="zipCode",fieldType=FieldType.postCode)
			}
	)
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public String save(MemberDomain member, HttpServletResponse response){
		if(!VerifyUtil.verifyUsername(member.getUsername(), false)){
			throw new NoticeException("用户名格式不正确");
		}
		if(!memberService.isUnique("username", null, member.getUsername())){
			throw new NoticeException("登录帐号已存在!");
		}
		String error = PasswordUtil.validPwd(member.getPassword());
		if(StringUtils.isNotBlank(error)){
			throw new NoticeException(error);
		}
		if(!memberService.isUnique("email", null, member.getEmail())){
			throw new NoticeException("电子邮箱已被使用!");
		}
		if(StringUtils.isNotBlank(member.getMobile()) 
				&& !memberService.isUnique("mobile", null, member.getMobile())){
			throw new NoticeException("手机号码已被使用!");
		}
		member.setPassword(DigestUtils.md5Hex(member.getPassword()));
		memberService.persist(member);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
	/**
	 * 修改会员
	 * @param id 会员id
	 * @param model
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public String edit(@PathVariable Long id, Model model){
		MemberDomain member = memberService.find(id);
		if(member == null){
			throw new NoticeException("会员不存在!");
		}
		model.addAttribute("member", member);
		return "/admin/b2c/member/input";
	}

	/**
	 * 更新会员信息
	 * @param member
	 * @param response
	 * @return
	 */
	@Validations(
			requiredFields = {
					@RequiredFieldValidator(fieldName="id",message="会员不存在")
			},
			requiredStrings = {
					@RequiredStringValidator(fieldName="email",message="电子邮箱不能为空")
			},
			specials = {
					@SpecialRegexFieldValidator(fieldName="mobile",fieldType=FieldType.mobile),
					@SpecialRegexFieldValidator(fieldName="telephone",fieldType=FieldType.telephone),
					@SpecialRegexFieldValidator(fieldName="email",fieldType=FieldType.email),
					@SpecialRegexFieldValidator(fieldName="zipCode",fieldType=FieldType.postCode)
			}
	)
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public String update(MemberDomain member, HttpServletResponse response){
		MemberDomain current = memberService.find(member.getId());
		if(current == null){
			throw new NoticeException("会员不存在!");
		}
		if(StringUtils.isNotBlank(member.getPassword())){
			String error = PasswordUtil.validPwd(member.getPassword());
			if(StringUtils.isNotBlank(error)){
				throw new NoticeException(error);
			}	
			current.setPassword(DigestUtils.md5Hex(member.getPassword()));
		}
		if(!memberService.isUnique("email", current.getEmail(), member.getEmail())){
			throw new NoticeException("电子邮箱已被使用!");
		}
		if(StringUtils.isNotBlank(member.getMobile()) 
				&& !memberService.isUnique("mobile", current.getMobile(), member.getMobile())){
			throw new NoticeException("手机号码已被使用!");
		}
		current.copyProperties(member);
		memberService.update(current);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
	/**
	 * 删除会员
	 * @param ids 会员ids
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	public String delete(Long[] ids, HttpServletResponse response){
		memberService.remove(ids);
		return ResponseUtils.renderJSON(successMessage, response);
	}

	/**
	 * 站内信关联会员查询
	 * @param keyword
	 * @param limit
	 * @return
	 */
	@RequestMapping(value="/search",method=RequestMethod.GET)
	@ResponseBody
	public JSONArray getMemberByUsername(String keyword, Integer limit){
		JSONArray arr = new JSONArray();
		String hql = "select bean from MemberDomain bean"
				+ " where bean.username like :keyword or bean.name like :keyword or bean.mobile like :keyword";
		Finder finder = Finder.create(hql);
		finder.setParam("keyword", keyword+"%");
		if(limit != null){
			finder.setMaxResults(limit);
		}
		List<MemberDomain> members = finder.findHQLList();
		if(!CollectionUtils.isEmpty(members)){
			for(MemberDomain member : members){
				JSONObject obj = new JSONObject();
				obj.put("id", member.getId());
				obj.put("username", member.getUsername());
				obj.put("mobile", member.getMobile());
				if(StringUtils.isNotBlank(member.getName())){
					obj.put("name", member.getName());
				}
				arr.add(obj);
			}
		}
		return arr;
	}

	@RequestMapping(value="/disable",method=RequestMethod.POST)
	@ResponseBody
	public Message disable(Long[] ids){
		memberService.disable(ids);
		return successMessage;
	}

	@RequestMapping(value="/enable",method=RequestMethod.POST)
	@ResponseBody
	public Message enable(Long[] ids){
		memberService.enable(ids);
		return successMessage;
	}

}
